﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using 畜牧业审核程序国产.Models;
using DataTable = System.Data.DataTable;
using Avalonia.Controls;
using 畜牧业审核程序国产.Views;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia;
using System.Text.RegularExpressions;
using System.IO.Compression;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using OpenQA.Selenium.DevTools.V126.Browser;
using Avalonia.Threading;
using MsBox.Avalonia.Enums;
using 畜牧业审核程序国产.Models.ToolsClass;
using OfficeOpenXml;
using System.Linq;
using SQLitePCL;
using 畜牧业审核程序国产.Models.ComparisonOutcome;
using Avalonia.Logging;
using Avalonia.Platform.Storage;

namespace 畜牧业审核程序国产.ViewModels;

internal enum 具体表号
{
    国网A209,
    A210,
    A211,
    A212,
    A406
}

internal enum 模板名称
{
    A209国网模板,
    A210模板,
    A211模板,
    A212模板,
    A406模板
}

public partial class Page1ViewModel : ViewModelBase
{
    #region 要用的年度和季度属性

    //本年度和本季度


    private int _intYearNow = DateTime.Now.Year;

    public int IntYearNow
    {
        get => _intYearNow;
        set
        {
            if (SetProperty(ref _intYearNow, value))
            {
                //SetStrYearNow();
                //SetStrSeasonNow();
                //SetYearOfPreSeason();
                //setYearOfYOYSeason();
                //SetSeasonPre();
                //SetSeasonYOY();
                Reset();
                Global.Reset(IntYearNow, IntSeasonNow);
                //Global.SetPlatform();已经放在reset里面了
                //ResetDownLoadButtonsEnable();没用了
                SendMsgToMainViewModel("YearChanged");
                // ChangeDtOfTableMsgs();
                InitializeDT();
            }
        }
    }

    private int _intSeasonNow;

    public int IntSeasonNow
    {
        get => _intSeasonNow;
        set
        {
            if (SetProperty(ref _intSeasonNow, value))
            {
                //SetStrSeasonNow();
                //SetYearOfPreSeason();
                //setYearOfYOYSeason();
                //SetSeasonPre();
                //SetSeasonYOY();
                Reset();
                Global.Reset(IntYearNow, IntSeasonNow);
               // Global.SetPlatform();已经放在reset里面了
               // ResetDownLoadButtonsEnable();
                SendMsgToMainViewModel("SeasonChanged");
                // ChangeDtOfTableMsgs();
                InitializeDT();
            }
        }
    }


    [ObservableProperty] private string _strYearNow;

    [ObservableProperty] private string _strSeasonNow;

    //环比年度和季度
    [ObservableProperty] private string _strYearPre;

    [ObservableProperty] private string _strSeasonPre;

    [ObservableProperty] private int _intYearPre;

    [ObservableProperty] private int _intSeasonPre;

    //同比年度和季度
    [ObservableProperty] private int _intYearYOY;

    [ObservableProperty] private int _intSeasonYOY;

    [ObservableProperty] private string _strSeasonYOY;

    [ObservableProperty] private string _strYearYOY;

    #endregion

    #region 与文本框内容绑定的属性

    [ObservableProperty] private string _textSchedule;
    [ObservableProperty] private bool _isSelectAllSeasons;

    #endregion

    #region 账号密码属性

    private string _str国网账号;

    public string Str国网账号
    {
        get { return _str国网账号; }
        set { SetProperty(ref _str国网账号, value); }
    }

    [ObservableProperty] private string _str国网密码;
    [ObservableProperty] private string _str省网账号;
    [ObservableProperty] private string _str省网密码;
    [ObservableProperty] private string _str统计云账号;
    [ObservableProperty] private string _str统计云密码;

    #endregion

    #region 保存用户名和密码要用到的settingManager

    private SettingManager _settingManager;

    #endregion

    #region 点击按钮时是否要同时下载环比季度和同比季度

    [ObservableProperty] private bool _isDownloadAll;

    #endregion

    #region 一套表和统计云根据季度，其是否可用的布尔属性

    private bool _isGetDataFromOldEnableNow;

    public bool IsGetDataFromOldEnableNow
    {
        get { return _isGetDataFromOldEnableNow; }
        set => SetProperty(ref _isGetDataFromOldEnableNow, value);
    }

    private bool _isGetDataFromOldEnablePre;

    public bool IsGetDataFromOldEnablePre
    {
        get { return _isGetDataFromOldEnablePre; }
        set => SetProperty(ref _isGetDataFromOldEnablePre, value);
    }

    private bool _isGetDataFromOldEnableYOY;

    public bool IsGetDataFromOldEnableYOY
    {
        get { return _isGetDataFromOldEnableYOY; }
        set => SetProperty(ref _isGetDataFromOldEnableYOY, value);
    }

    private bool _isGetDataFromCloudStatsEnableNow;

    public bool IsGetDataFromCloudStatsEnableNow
    {
        get { return _isGetDataFromCloudStatsEnableNow; }
        set => SetProperty(ref _isGetDataFromCloudStatsEnableNow, value);
    }

    private bool _isGetDataFromCloudStatsEnablePre;

    public bool IsGetDataFromCloudStatsEnablePre
    {
        get { return _isGetDataFromCloudStatsEnablePre; }
        set => SetProperty(ref _isGetDataFromCloudStatsEnablePre, value);
    }

    private bool _isGetDataFromCloudStatsEnableYOY;

    public bool IsGetDataFromCloudStatsEnableYOY
    {
        get { return _isGetDataFromCloudStatsEnableYOY; }
        set => SetProperty(ref _isGetDataFromCloudStatsEnableYOY, value);
    }

    #endregion

    #region 声明命令

    public RelayCommand 导入压缩包Command { get; }

    //public RelayCommand 打开debug文件夹Command { get; }
    public RelayCommand AuditCommand { get; }
    public RelayCommand GetDataFromOldCommand { get; }
    public RelayCommand Get国网CommandPre { get; }
    public RelayCommand<string> GetYoYDataCommand { get; }
    public RelayCommand 结果过录Command { get; }
    public RelayCommand 县乡名称修正Command { get; }
    public RelayCommand GetDataFromStatsCloudCommand { get; }
    public RelayCommand<string> GetDataFromOldCommandP { get; set; }
    public RelayCommand OpenPasteWindowCommand { get; private set; }
    public RelayCommand DataCompairisonCommand { get; private set; }
    public RelayCommand OpenAuditFolderPathCommand { get; private set; }
    public RelayCommand ReplaceTextInSqliteCommand { get; private set; }
    public RelayCommand OverRecordCommand { get; private set; }
    public RelayCommand OpenUserInfoCommand { get; private set; }
    public RelayCommand ModifyCityCoutryTownCommand { get; private set; }
    public RelayCommand OpenLogPathCommand { get; private set; }
    public RelayCommand DeleteSingleTableInDBCommand { get; private set; }
    #endregion

    //进度条,还是在方法里面初始化吧
    //private MyProgressBar _progressBar;

    #region 构造函数

    public Page1ViewModel()
    {
        //在桌面建立文件夹();
        //MyDataFolderOperator.CopyDBtoDesktopFolder();
        MyDataFolderOperator.CreateOrCheckAuditProgramFolderExist();

        InitializeDefaultYearAndSeason(); //初始化当前所属的年度和季度
        //StrSeasonNow = "第二季度";
        //TestSeason = "第二季度";
        _settingManager = new SettingManager();
        InitiazeAcountInfo();
        InitializeDT();
        //ResetDownLoadButtonsEnable();
       // GetDataFromOldCommand = new RelayCommand(async () => await ExecuteGetDataFromOld());
       // this.Get国网CommandPre = new RelayCommand(() => 在桌面建立文件夹());
        // this.GetDataFromOldCommandP = new RelayCommand<string>((p) => ExecuteGetDataFromOld(p));
        this.导入压缩包Command = new RelayCommand(async () => await UseDownLoadedAsync());
        this.AuditCommand = new RelayCommand(async () => await AuditAsync());
        //this.GetDataFromStatsCloudCommand = new RelayCommand(async () => await ExecuteGetDataFromStatsCloud());
        this.OpenPasteWindowCommand = new RelayCommand(async () => await OpenPasteWindowAsync());
        this.DataCompairisonCommand = new RelayCommand(async () => await DataComparison());
        this.OpenAuditFolderPathCommand = new RelayCommand(() => OpenAuditFolder());
        this.ReplaceTextInSqliteCommand = new RelayCommand(() => ReplaceTextInSqlite());
        this.OverRecordCommand = new RelayCommand(new Action(async () => await OverRecordAsync()));
        this.OpenUserInfoCommand = new RelayCommand(async () => await OpenUserImformationAsync());
        this.ModifyCityCoutryTownCommand = new RelayCommand(async () => await ModifyCityCountryTownAsync());
        this.OpenLogPathCommand = new RelayCommand(() => OpenLogPath());
        this.DeleteSingleTableInDBCommand = new RelayCommand(async () => await DeleteSingleTableInDBAsync());
    }
    #endregion
    #region 打开日志路径,已废弃
    private void OpenLogPath()
    {
        // 通过 NLog 配置文件获取日志文件路径
        // 例如日志文件路径为 "logs/2024-11-20System.log"
        string baseDir = AppDomain.CurrentDomain.BaseDirectory;
        string logFileName = $"{DateTime.Now:yyyy-MM-dd}System.log";
        string logFilePath = Path.Combine(baseDir, "logs", logFileName);


        // 获取文件所在的文件夹路径
        string logFolderPath = Path.GetDirectoryName(logFilePath);
        if (Directory.Exists(logFolderPath))
        {
            try
            {
                // 检查操作系统
                if (OperatingSystem.IsWindows())
                {
                    Process.Start("explorer.exe", logFolderPath);
                }
                else if (OperatingSystem.IsLinux())
                {
                    // 使用 xdg-open 打开文件夹
                    Process.Start("xdg-open", logFolderPath);
                }
                else if (OperatingSystem.IsMacOS())
                {
                    // 使用 open 打开文件夹
                    Process.Start("open", logFolderPath);
                }
                else
                {
                    Console.WriteLine("不支持的操作系统。");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"打开文件夹失败: {ex.Message}");
            }
        }
        else
        {
            Console.WriteLine("指定的文件夹不存在。");
        }
    }
#endregion
    private async Task OverRecordAsync()
    {
        try
        {
            StaticLogger.SystemInfo("开始过录操作");
            FuncOutCome overRecordOutcome;
            var mainWindow = GetMainWindow();

            //var topLevel = TopLevel.GetTopLevel(mainWindow);
            //// 启动异步操作以打开对话框。
            //var file = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
            //{
            //    Title = "选择已经写过审核说明的旧审核结果",
            //    AllowMultiple = false,
            //    SuggestedStartLocation = 

            //});

            var openFileDialogOld = new OpenFileDialog()
            {
                Directory = MyDataFolderOperator.AuditOutcomeFolderPathInAuditProgramFolder,
                Title = "选择已经写过审核说明的旧审核结果",
                AllowMultiple = false, // 不允许多选
            };
            // 添加文件类型过滤器（可选）
            openFileDialogOld.Filters.Add(new FileDialogFilter
            {
                Name = "旧的审核结果",
                Extensions = { "xlsx" }
            });
            //var openFileDialogOld = mainWindow.StorageProvider.OpenFilePickerAsync(new Avalonia.Platform.Storage.FilePickerOpenOptions
            //{
            //    Title = "选择已经写过审核说明的旧审核结果",
            //    AllowMultiple = false,
            //    SuggestedStartLocation = MyDataFolderOperator.AuditOutcomeFolderPathInAuditProgramFolder,
            //});
            //{
            //    Directory = MyDataFolderOperator.AuditOutcomeFolderPathInAuditProgramFolder,
            //    Title = "选择已经写过审核说明的旧审核结果",
            //    AllowMultiple = false, // 不允许多选
            //};
            //// 添加文件类型过滤器（可选）
            //openFileDialogOld.Filters.Add(new FileDialogFilter
            //{

            //    Name = "旧的审核结果",
            //    Extensions = { "xlsx" }
            //});

            // 打开对话框并获取结果
            var resultsOld = await openFileDialogOld.ShowAsync(mainWindow);
            //if (results != null && results.Length > 0)
            //{//这里无需判断选择的文件是否是excel
            //    //string oldExcelPath = results[0];
            //    //string extensionOfOldExcelPath = System.IO.Path.GetExtension(oldExcelPath).ToLower();
            //    //if (extensionOfOldExcelPath.Equals(".xlsx") == false)
            //    //{
            //    //    await MyMessagebox.ShowAsyncInMainWindow("选择的文件不是excel")
            //    //}

            //}
            if (resultsOld.FirstOrDefault() == null)
            {
                await MyMessagebox.ShowAsyncInMainWindow("未选择旧审核结果Excel文件!", Icon.Error, ButtonEnum.Ok);
                return;
            }

            var openFileDialogNew = new OpenFileDialog()
            {
                Directory = MyDataFolderOperator.AuditOutcomeFolderPathInAuditProgramFolder,
                Title = "选择最新的审核结果",
                AllowMultiple = false, // 不允许多选
            };
            // 添加文件类型过滤器（可选）
            openFileDialogNew.Filters.Add(new FileDialogFilter
            {
                Name = "新的审核结果",
                Extensions = { "xlsx" }
            });
            var resultNew = await openFileDialogNew.ShowAsync(mainWindow);
            if (resultNew.FirstOrDefault() == null)
            {
                await MyMessagebox.ShowAsyncInMainWindow("未选择新审核结果Excel文件!", Icon.Error, ButtonEnum.Ok);
                return;
            }

            overRecordOutcome = OverRecordFunc.OverRecord(resultsOld.FirstOrDefault(), resultNew.FirstOrDefault());
            await MyMessagebox.ShowAsyncInMainWindow(overRecordOutcome.SomeOtherInfo, overRecordOutcome.Icon,
                ButtonEnum.Ok);
            if (overRecordOutcome.FuncOutComeInfoArgs != null)
            {
                this.TextSchedule = overRecordOutcome.FuncOutComeInfoArgs;
            }

            StaticLogger.SystemInfo("过录完成");
        }
        catch (Exception ex)
        {
          
            StaticLogger.SystemError($"过录出错,错误信息为{ex.Message}");
            StaticLogger.SystemError($"堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");

            await MyMessagebox.ShowAsyncInMainWindow($"出现错误,错误内容为{ex.Message}", Icon.Error);
        }
    }

    private static void ReplaceTextInSqlite()
    {
        ReplaceText.ReplaceSomeText();
    }

    // 这是异步更新ui的方式吗=>: 获取 CPU 架构并在 UI 线程中更新 TextBlock
    //Dispatcher.UIThread.InvokeAsync(() =>
    //        {
    //            _textBlock.Text = $"当前 Linux 操作系统的 CPU 架构: {GetCpuArchitecture()}";
    //        });
    private async Task OpenPasteWindowAsync()
    {
        StaticLogger.SystemInfo("执行打开统计云粘贴窗口");
        Window window = new PasteDataFromStatsCloud();
        WeakReferenceMessenger.Default.Send(new TransmitView(window));
        await window.ShowDialog(GetMainWindow());
        MyMessage msg1 = new MyMessage("粘贴页面关闭");
        WeakReferenceMessenger.Default.Send(msg1);
        StaticLogger.SystemInfo("粘贴完成");
        InitializeDT();
    }

    public async Task OpenUserImformationAsync()
    {
        Window userInfoWindow = new UserInformation();
        WeakReferenceMessenger.Default.Send(new TransmitView(userInfoWindow));
        await userInfoWindow.ShowDialog(GetMainWindow());

        InitializeDT();
        MyMessage msg1 = new MyMessage("自动下载页面关闭");
        WeakReferenceMessenger.Default.Send(msg1);
    }

    private async Task ExecuteGetDataFromStatsCloud()
    {
        string[] Arr表名 = { "209", "210", "211", "212" };
        bool isGetDataFromStatsCloudSuccess = await 网络操作.GetMassInStatsCloud(Str统计云账号, Str统计云密码,
            MyDataFolderOperator.AuditProgramFolderPath, IntSeasonNow, Arr表名);
        if (isGetDataFromStatsCloudSuccess == true)
        {

            await MyMessagebox.ShowAsyncInMainWindow("全部导入成功!", Icon.Success);
            MyMessage msg1 = new MyMessage("Reload");
            WeakReferenceMessenger.Default.Send(msg1);
            InitializeDT();
        }
    }

    private async Task AuditAsync()
    {
        StaticLogger.SystemInfo("执行审核操作");
        this.TextSchedule = string.Empty;
        this.TextSchedule += "开始审核..." + Environment.NewLine;
        //开始导入
        MyProgressBar _progressBar = new MyProgressBar();
        _progressBar.Show();
        var progress = new Progress<int>(value => _progressBar.UpdateProgress(value));
        FuncOutCome auditOutCome = await Task.Run(() => AuditFunc.Audit(this.StrYearNow, this.StrSeasonNow,
            this.StrYearPre, this.StrSeasonPre, this.StrYearYOY, this.StrSeasonYOY, progress));
        _progressBar.Close();

        if (auditOutCome.Icon == Icon.Success)
        {
            this.TextSchedule += auditOutCome.FuncOutComeInfoArgs + Environment.NewLine;
            await MyMessagebox.ShowAsyncInMainWindow("数据审核成功,请在桌面的审核程序文件夹查看!", auditOutCome.Icon);
            StaticLogger.SystemInfo("审核操作完成,没有出现错误或警告");
        }
        else
        {
            this.TextSchedule += auditOutCome.FuncOutComeInfoArgs + Environment.NewLine;
            await MyMessagebox.ShowAsyncInMainWindow("数据审核结束,审核过程中有问题或警告,请查看文本框或日志!", auditOutCome.Icon);


            //if (auditOutCome.FuncSuccessCode == FuncOutComeCodeType.NullError)
            //{
            //    this.TextSchedule += auditOutCome.FuncOutComeInfoArgs + Environment.NewLine;
            //    await MyMessagebox.ShowAsyncInMainWindow("数据审核结束,至少有一个畜种报表未导入到本地数据,请查看文本框!", auditOutCome.Icon);
            //}
            //else if (auditOutCome.FuncSuccessCode == FuncOutComeCodeType.LosePreSeasonError)
            //{
            //    this.TextSchedule += auditOutCome.FuncOutComeInfoArgs + Environment.NewLine;
            //    await MyMessagebox.ShowAsyncInMainWindow("数据审核结束,至少有一个上季度报表未导入到本地数据导致有公式未审核,请查看文本框!", auditOutCome.Icon);
            //}
            //else if (auditOutCome.FuncSuccessCode == FuncOutComeCodeType.LoseA406Error)
            //{
            //    this.TextSchedule += auditOutCome.FuncOutComeInfoArgs + Environment.NewLine;
            //    await MyMessagebox.ShowAsyncInMainWindow("数据审核结束,本季度A406表未导入,规模户与全面的审核关系未审核,请查看文本框!", auditOutCome.Icon);
            //}
            //else
            //{
            //    this.TextSchedule += auditOutCome.FuncOutComeInfoArgs + Environment.NewLine;
            //    await MyMessagebox.ShowAsyncInMainWindow("数据审核过程中出现错误,请看文本框或日志!", auditOutCome.Icon);
            //}
            StaticLogger.SystemInfo("审核操作完成,但有错误或警告");
            StaticLogger.SystemInfo($"内容为:{auditOutCome.FuncOutComeInfoArgs}");
        }
    }

    /// <summary>
    /// 获取程序的主窗口,用来给MyMessagebox使用
    /// </summary>
    /// <returns></returns>
    private Window GetMainWindow()
    {
        if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            return desktop.MainWindow;
        }

        return null;
    }

    private async Task UseDownLoadedAsync()
    {
        try
        {
            StaticLogger.SystemInfo("开始执行导入一套表数据功能");
            this.TextSchedule = string.Empty;
            var mainWindow = GetMainWindow();
            if (mainWindow != null)
            {
                var openFileDialog = new OpenFileDialog()
                {
                    Title = "选择文件",
                    AllowMultiple = true, // 允许多选
                };
                // 添加文件类型过滤器（可选）
                openFileDialog.Filters.Add(new FileDialogFilter
                {
                    Name = "一套表下载的压缩包(zip)",
                    Extensions = { "zip" }
                });
                openFileDialog.Filters.Add(new FileDialogFilter
                {
                    Name = "Excel文件(xls)",
                    Extensions = { "xls" }
                });

                // 打开对话框并获取结果
                var results = await openFileDialog.ShowAsync(mainWindow);
                if (results != null && results.Length > 0)
                {
                    // 处理选中的文件路径
                    //foreach (var filePath in results)
                    //{
                    //   // MyMessagebox.Show($"选中的文件路径: {filePath}");
                    //   await MyMessagebox.ShowAsync($"选中的文件路径: {filePath}", mainWindow);
                    //   // await MyMessagebox.ShowAsync($"主窗口标题是{mainWindow.Title}", mainWindow);
                    //}


                    ////怎么没用啊
                    //await Dispatcher.UIThread.InvokeAsync(() =>
                    //            {
                    //                this.TextSchedule += $"开始导入数据";
                    //            });


                    if (Regex.IsMatch(results[0].Substring(results[0].Length - 2, 2), "ip") == true) //说明选中的是压缩包
                    {
                        // 获取选择的第一个文件的路径
                        string firstzipFilePath = results[0];
                        // 获取文件所在文件夹的路径
                        string zipDirectoryPath = Path.GetDirectoryName(firstzipFilePath);
                        //先删除名为"ExtractPath"的文件夹,并创建一个新的文件夹名
                        string zipExtractFolderPath = Path.Combine(zipDirectoryPath, "ExtractPath");
                        //创建文件夹
                        try
                        {
                            if (Directory.Exists(zipExtractFolderPath))
                            {
                                Directory.Delete(zipExtractFolderPath, recursive: true); //加true,表示删除这个文件夹里面的子文件夹和文件
                            }

                            Directory.CreateDirectory(zipExtractFolderPath);
                            for (int i = 0; i < results.Length; i++)//把选中的压缩包全部解压到这个文件夹中
                            {
                                ZipFile.ExtractToDirectory(results[i], zipExtractFolderPath, true);
                            }

                            //获取解压后的文件夹内所有的xls文件
                            string[] allXlsFilesPath =
                                Directory.GetFiles(zipExtractFolderPath, "*.xls", SearchOption.TopDirectoryOnly);
                            if (allXlsFilesPath.Length == 0)
                            {
                                await MyMessagebox.ShowAsyncInMainWindow("压缩包解压后没有xls文件!", Icon.Error);
                                return;
                            }

                            //开始导入
                            MyProgressBar _progressBar = new MyProgressBar();
                            _progressBar.Show();
                            var progress = new Progress<int>(value => _progressBar.UpdateProgress(value));
                            FuncOutCome funcOutCome = await Task.Run(() =>
                                XlsToSqlite.ExportXlsFilesToSqlite(allXlsFilesPath, progress));
                            _progressBar.Close();
                            if (funcOutCome.FuncSuccessCode == FuncOutComeCodeType.Success)
                            {
                                this.TextSchedule = "导入成功!";
                                StaticLogger.SystemInfo("一套表导入成功");
                                await MyMessagebox.ShowAsyncInMainWindow("导入成功!", Icon.Success);
                                MyMessage msg1 = new MyMessage("reload");
                                WeakReferenceMessenger.Default.Send(msg1);
                                InitializeDT();
                            }
                            else
                            {
                                StaticLogger.SystemError($"导入出错,错误内容为:{funcOutCome.FuncOutComeInfoArgs}");
                                this.TextSchedule = funcOutCome.FuncOutComeInfoArgs + Environment.NewLine;
                                await MyMessagebox.ShowAsyncInMainWindow("导入有错误,请查看文本框", Icon.Info);
                            }
                        }
                        catch (Exception ex)
                        {
                            StaticLogger.SystemError($"导入出错,错误内容为:{ex.Message}");
                            this.TextSchedule = ex.Message + Environment.NewLine;
                            await MyMessagebox.ShowAsyncInMainWindow($"出现错误,错误内容为{ex.Message}", Icon.Error);
                            return;
                        }
                    }

                    else if (Regex.IsMatch(results[0].Substring(results[0].Length - 2, 2), "ls") == true) //说明选中的是excel文件
                    {
                        try
                        {
                            //开始导入
                            MyProgressBar _progressBar = new MyProgressBar();
                            _progressBar.Show();
                            var progress = new Progress<int>(value => _progressBar.UpdateProgress(value));
                            FuncOutCome funcOutCome =
                                await Task.Run(() => XlsToSqlite.ExportXlsFilesToSqlite(results, progress));
                            _progressBar.Close();
                            if (funcOutCome.FuncSuccessCode == FuncOutComeCodeType.Success)
                            {
                                this.TextSchedule = "导入成功!";
                                StaticLogger.SystemInfo("一套表导入成功");
                                await MyMessagebox.ShowAsyncInMainWindow("导入成功!", Icon.Success);
                                MyMessage msg1 = new MyMessage("reload");
                                WeakReferenceMessenger.Default.Send(msg1);
                                InitializeDT();
                            }
                            else
                            {
                                this.TextSchedule = funcOutCome.FuncOutComeInfoArgs + Environment.NewLine;
                                StaticLogger.SystemError($"导入出错,错误内容为:{funcOutCome.FuncOutComeInfoArgs}");
                                await MyMessagebox.ShowAsyncInMainWindow("导入有错误,请查看文本框", Icon.Info);
                            }
                        }
                        catch (Exception ex)
                        {
                            StaticLogger.SystemError($"导入出错,错误内容为:{ex.Message}");
                            this.TextSchedule = ex.Message + Environment.NewLine;
                            await MyMessagebox.ShowAsyncInMainWindow($"出现错误,错误内容为{ex.Message}", Icon.Error);
                        }
                    }
                    else
                    {
                        StaticLogger.SystemError("导入出错,错误内容为:选取的文件存在非zip压缩包或非xls文件");
                        await MyMessagebox.ShowAsync($"所选取的文件中存在非zip压缩包或非xls文件!", mainWindow, icon: Icon.Warning);
                        return;
                    }

                    //解压缩 并读取导入到数据库中
                    //先在这些zip所在的文件夹下建立一个解压文件存放的文件夹


                    //////// 获取选择的第一个文件的路径
                    //////string firstXlsFilePath = results[0];
                    //////// 获取文件所在文件夹的路径
                    //////string DirectoryPath = Path.GetDirectoryName(firstXlsFilePath);
                    ////////先删除名为"ExtractPath"的文件夹,并创建一个新的文件夹名
                    //////string extractFolderPath = Path.Combine(DirectoryPath, "ExtractPath");
                    ////////创建文件夹
                    //////try
                    //////{
                    //////    if (Directory.Exists(extractFolderPath))
                    //////    {
                    //////        Directory.Delete(extractFolderPath, recursive: true);//加true,表示删除这个文件夹里面的子文件夹和文件
                    //////    }
                    //////    Directory.CreateDirectory(extractFolderPath);
                    //////}
                    //////catch (Exception ex)//如果文件夹已经存在了
                    //////{
                    //////    await MyMessagebox.ShowAsyncInMainWindow($"出现错误,错误内容为{ex.Message}", Icon.Error);
                    //////    throw;
                    //////}
                    //////MyProgressBar progressBar = new MyProgressBar();
                    ////////把所有的results里的压缩包全部解压到这个新的文件夹中
                    //////for (int i = 0; i < results.Length; i++)
                    //////{
                    //////    ZipFile.ExtractToDirectory(results[i], extractFolderPath, true);
                    //////}
                    //////this.TextSchedule = null;
                    //////this.TextSchedule += "导入完成";


                    ////////把xls文件写入到数据库中
                    //////bool isAllImportSuccess = await XlsToSqlite.ExportXlsFilesToSqlite(extractFolderPath);


                    ////////删掉解压文件夹,避免用户疑问
                    //////if (Directory.Exists(extractFolderPath))
                    //////{
                    //////    Directory.Delete(extractFolderPath, true);
                    //////}
                    //////MyMessage msg1 = new MyMessage("reload");
                    //////WeakReferenceMessenger.Default.Send(msg1);
                    //////InitializeDT();
                }
                else
                {
                    StaticLogger.SystemInfo("用户取消导入操作");
                }
                // Global.SetPlatform();
            }
        }
        catch (Exception ex)
        {
            StaticLogger.SystemError($"粘贴出错,错误信息为{ex.Message}");
            StaticLogger.SystemError($"堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");

            await MyMessagebox.ShowAsyncInMainWindow($"出现错误,错误内容为{ex.Message}", Icon.Error);
        }
    }

    private void InitiazeAcountInfo()
    {
        this.Str国网账号 = _settingManager.Str国网Account;
        this.Str国网密码 = _settingManager.Str国网Password;
        this.Str省网账号 = _settingManager.Str省网Account;
        this.Str省网密码 = _settingManager.Str省网Password;
        this.Str统计云账号 = _settingManager.StrCloudAccount;
        this.Str统计云密码 = _settingManager.StrCloudPassword;
    }

    

    #region 与View上的Datagrid绑定,wpf是datatable就可以了,这里必须是observableCollection(TableMsgs)

    private ObservableCollection<TableMsgs> _myTableMsgs = new ObservableCollection<TableMsgs>();

    public ObservableCollection<TableMsgs> MyTableMsgs
    {
        get { return _myTableMsgs; }
        set { SetProperty(ref _myTableMsgs, value); }
    }

    private DataTable _dtOfTableMsgs;

    public DataTable DtOfTableMsgs
    {
        get { return _dtOfTableMsgs; }
        set => SetProperty(ref _dtOfTableMsgs, value);
    }
    [ObservableProperty]
    private TableMsgs _selectedTableMsgs;
    //private ObservableCollection<TableMsgs> _tableMsgs;

    //public ObservableCollection<TableMsgs> tableMsgs
    //{
    //    get { return _tableMsgs; }
    //    set { _tableMsgs = value; }
    //}
    //  public ObservableCollection<TableMsgs> MyTableMsgs { get; set; }

    #endregion

    #region Func_把从数据库里获取到的datatable的第一列第二列第三列分别赋值给一个tablemsgs对象,对象最后就是一个observable集合

    /// <summary>
    /// 初始化当前选择的季度以及其环比季度、同比季度的各畜种报表在数据库中的情况
    /// </summary>
    public void InitializeDT()
    {
        //MyDBOperator dBOperator = new MyDBOperator();改用单例模式
        MyDBOperator dBOperator = MyDBOperator.DBOperatorInstance;
        //获取到
        // DtOfTableMsgs = dBOperator.ShowAllNeedTableMsgs(StrYearNow, StrSeasonNow, StrYearPre, StrSeasonPre, StrYearYOY,StrSeasonYOY);
        DtOfTableMsgs = ShowAllNeedTableMsgs();
        MyTableMsgs.Clear();
        for (int i = 0; i < DtOfTableMsgs.Rows.Count; i++)
        {
            DataRow row = DtOfTableMsgs.Rows[i];
            MyTableMsgs.Add(new TableMsgs(row[0].ToString(), row[1].ToString(), row[2].ToString()));
        }
    }
    /// <summary>
    /// 根据传进来的当前年度当前季度、环比年度环比季度、同比年度同比季度，再在其前面加上“一套表”或者"统计云",把表的名称\导入时间\创建时间形成一个datatable并返回去
    /// </summary>
    /// <param name="stryearnow"></param>
    /// <param name="strseasonnow"></param>
    /// <param name="stryearpre"></param>
    /// <param name="strseasonpre"></param>
    /// <param name="stryearyoy"></param>
    /// <param name="strseasonyoy"></param>
    /// <returns></returns>
    public DataTable ShowAllNeedTableMsgs()
    {
        DataTable DTOfTableMsgs = new DataTable();
        string[] allNeedTableNames = null;
        if (IntYearNow < 2024 || (IntYearNow == 2024 && IntSeasonNow <= 2))//2024年三季度前,本季度\环比季度\同比季度都是一套表的
        {
            allNeedTableNames = new string[] {
                    $"一套表{StrYearNow}{StrSeasonNow}A209", $"一套表{StrYearNow}{StrSeasonNow}A210",
                    $"一套表{StrYearNow}{StrSeasonNow}A211", $"一套表{StrYearNow}{StrSeasonNow}A212",
                    $"一套表{StrYearNow}{StrSeasonNow}A406",
                    $"一套表{StrYearPre}{StrSeasonPre}A209", $"一套表{StrYearPre}{StrSeasonPre}A210",
                    $"一套表{StrYearPre}{StrSeasonPre}A211", $"一套表{StrYearPre}{StrSeasonPre}A212",
                    $"一套表{StrYearPre}{StrSeasonPre}A406",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A209", $"一套表{StrYearYOY}{StrSeasonYOY}A210",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A211", $"一套表{StrYearYOY}{StrSeasonYOY}A212",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A406"
            };
        }
        else if (IntYearNow == 2024 && IntSeasonNow == 3)//2024年三季度,本表是统计云,环比用表和同比用表是一套表
        {
            allNeedTableNames = new string[] {
                    $"统计云{StrYearNow}{StrSeasonNow}A209", $"统计云{StrYearNow}{StrSeasonNow}A210",
                    $"统计云{StrYearNow}{StrSeasonNow}A211", $"统计云{StrYearNow}{StrSeasonNow}A212",
                    $"一套表{StrYearNow}{StrSeasonNow}A406",
                    $"一套表{StrYearPre}{StrSeasonPre}A209", $"一套表{StrYearPre}{StrSeasonPre}A210",
                    $"一套表{StrYearPre}{StrSeasonPre}A211", $"一套表{StrYearPre}{StrSeasonPre}A212",
                    $"一套表{StrYearPre}{StrSeasonPre}A406",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A209", $"一套表{StrYearYOY}{StrSeasonYOY}A210",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A211", $"一套表{StrYearYOY}{StrSeasonYOY}A212",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A406",
                    $"一套表{StrYearNow}{StrSeasonNow}A209", $"一套表{StrYearNow}{StrSeasonNow}A210",
                    $"一套表{StrYearNow}{StrSeasonNow}A211", $"一套表{StrYearNow}{StrSeasonNow}A212",
                    $"一套表{StrYearNow}{StrSeasonNow}A406"
            };
        }
        else if ((IntYearNow == 2024 && IntSeasonNow == 4) || IntYearNow == 2025 && IntSeasonNow == 1)//2024年四季度到2025年一季度,本表和环比是统计云,同比用表是一套表
        {
            allNeedTableNames = new string[] {
                    $"统计云{StrYearNow}{StrSeasonNow}A209", $"统计云{StrYearNow}{StrSeasonNow}A210",
                    $"统计云{StrYearNow}{StrSeasonNow}A211", $"统计云{StrYearNow}{StrSeasonNow}A212",
                    $"一套表{StrYearNow}{StrSeasonNow}A406",
                    $"统计云{StrYearPre}{StrSeasonPre}A209", $"统计云{StrYearPre}{StrSeasonPre}A210",
                    $"统计云{StrYearPre}{StrSeasonPre}A211", $"统计云{StrYearPre}{StrSeasonPre}A212",
                    $"一套表{StrYearPre}{StrSeasonPre}A406",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A209", $"一套表{StrYearYOY}{StrSeasonYOY}A210",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A211", $"一套表{StrYearYOY}{StrSeasonYOY}A212",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A406"
            };
        }
        else 
        {
            allNeedTableNames = new string[] {
                    $"统计云{StrYearNow}{StrSeasonNow}A209", $"统计云{StrYearNow}{StrSeasonNow}A210",
                    $"统计云{StrYearNow}{StrSeasonNow}A211", $"统计云{StrYearNow}{StrSeasonNow}A212",
                    $"一套表{StrYearNow}{StrSeasonNow}A406",
                    $"统计云{StrYearPre}{StrSeasonPre}A209", $"统计云{StrYearPre}{StrSeasonPre}A210",
                    $"统计云{StrYearPre}{StrSeasonPre}A211", $"统计云{StrYearPre}{StrSeasonPre}A212",
                    $"一套表{StrYearPre}{StrSeasonPre}A406",
                    $"统计云{StrYearYOY}{StrSeasonYOY}A209", $"统计云{StrYearYOY}{StrSeasonYOY}A210",
                    $"统计云{StrYearYOY}{StrSeasonYOY}A211", $"统计云{StrYearYOY}{StrSeasonYOY}A212",
                    $"一套表{StrYearYOY}{StrSeasonYOY}A406"
            };
        }

        MyDBOperator getTableMsgOperator = MyDBOperator.DBOperatorInstance;
        DTOfTableMsgs = getTableMsgOperator.GetDataTable("select 表名称,导入时间,已导入的户数 from DataTable要用的字段 "); //手动创建的datatable显示不了,这里是获取标题
                                                                                     // DTOfTableMsgs = new DataTable();
                                                                                     //DTOfTableMsgs.Columns.Add("表名", typeof(string));
                                                                                     //DTOfTableMsgs.Columns.Add("导入时间", typeof(string));
        foreach (string tablename in allNeedTableNames)
        {
            int rowcount;
            string TableCreateTime =getTableMsgOperator.ReturnTableCreateTimeAndRowCount(tablename, out rowcount);
            DataRow tableMsgRow = DTOfTableMsgs.NewRow();
            tableMsgRow[0] = tablename;
            tableMsgRow[1] = TableCreateTime;
            tableMsgRow[2] = rowcount;
            DTOfTableMsgs.Rows.Add(tableMsgRow);
        }

        //DTOfTableMsgs.Columns[0].ColumnName = "表名";
        //DTOfTableMsgs.Columns[1].ColumnName = "是否导入";
        return DTOfTableMsgs;
    }
    #endregion

    /*
    /// <summary>
    /// 重新设置这三行6个按钮的功能是否可用
    /// </summary>
    public void ResetDownLoadButtonsEnable()
    {
        if (this.IntYearNow <= 2024)
        {
            IsGetDataFromOldEnableNow = true;
        }
        else
        {
            IsGetDataFromOldEnableNow = false;
        }


        if (this.IntYearPre <= 2024)
        {
            IsGetDataFromOldEnablePre = true;
        }
        else
        {
            IsGetDataFromOldEnablePre = false;
        }

        if (this.IntYearYOY <= 2024)
        {
            IsGetDataFromOldEnableYOY = true;
        }
        else
        {
            IsGetDataFromOldEnableYOY = false;
        }

        if (this.IntYearNow > 2024 || (this.IntYearNow == 2024 && this.IntSeasonNow >= 2))
        {
            IsGetDataFromCloudStatsEnableNow = true;
        }
        else
        {
            IsGetDataFromCloudStatsEnableNow = false;
        }

        if (this.IntYearPre > 2024 || (this.IntYearPre == 2024 && this.IntSeasonPre >= 2))
        {
            IsGetDataFromCloudStatsEnablePre = true;
        }
        else
        {
            IsGetDataFromCloudStatsEnablePre = false;
        }

        if (this.IntYearYOY > 2024 || (this.IntYearYOY == 2024 && this.IntSeasonYOY >= 2))
        {
            IsGetDataFromCloudStatsEnableYOY = true;
        }
        else
        {
            IsGetDataFromCloudStatsEnableYOY = false;
        }
    }
    */

    /*private void 在桌面建立文件夹()
    {
        // MyDataFolderOperator.GetOrSetDataFolderPathOnDesk("ava畜牧业审核程序");
        MyDataFolderOperator.CreateOrCheckAuditProgramFolderExist();
    }*/


    [ObservableProperty] private string _testSeason;

    #region Func_根据当前的时间初始化当前所属的年度和季度

    /// <summary>
    /// 根据当前的时间初始化当前所属的年度和季度
    /// </summary>
    private void InitializeDefaultYearAndSeason()
    {
        IntYearNow = DateTime.Now.Year;
        StrYearNow = _intYearNow + "年";
        //报表的期别为上季度末26号到本季度末25号,但是二季度肯定是关注一季度的数据，因此当处于二季度时，仍然默认显示一季度的
        var spring = new DateTime(DateTime.Now.Year, 3, 25);
        var summer = new DateTime(DateTime.Now.Year, 6, 25);
        var autumn = new DateTime(DateTime.Now.Year, 9, 25);
        var winter = new DateTime(DateTime.Now.Year, 12, 25);
        //以下其实可以用global里面的方法进行设置
        if (DateTime.Now >= spring && DateTime.Now < summer)
        {
            IntSeasonNow = 1;
            StrSeasonNow = "第一季度";
            //设置前一季度的年度和季度
            IntYearPre = IntYearNow - 1;
            StrYearPre = IntYearPre + "年";
            IntSeasonPre = 4;
            StrSeasonPre = "第四季度";
            //设置同比季度的年度和季度
            IntYearYOY = IntYearNow - 1;
            StrYearYOY = IntYearYOY + "年";
            IntSeasonYOY = 1;
            StrSeasonYOY = "第一季度";
        }
        else if (DateTime.Now >= summer && DateTime.Now < autumn)
        {
            IntSeasonNow = 2;
            StrSeasonNow = "第二季度";
            //设置前一季度的年度和季度 其实变量名应该写intyearofpreseson的
            IntYearPre = IntYearNow;
            StrYearPre = IntYearPre + "年";
            IntSeasonPre = 1;
            StrSeasonPre = "第一季度";
            //设置同比季度的年度和季度
            IntYearYOY = IntYearNow - 1;
            StrYearYOY = IntYearYOY + "年";
            IntSeasonYOY = 2;
            StrSeasonYOY = "第二季度";
        }
        else if (DateTime.Now >= autumn && DateTime.Now < winter)
        {
            IntSeasonNow = 3;
            StrSeasonNow = "第三季度";
            //设置前一季度的年度和季度 其实变量名应该写intyearofpreseson的
            IntYearPre = IntYearNow;
            StrYearPre = IntYearPre + "年";
            IntSeasonPre = 2;
            StrSeasonPre = "第二季度";
            //设置同比季度的年度和季度
            IntYearYOY = IntYearNow - 1;
            StrYearYOY = IntYearYOY + "年";
            IntSeasonYOY = 3;
            StrSeasonYOY = "第三季度";
        }
        else
        {
            //在第一季度的时候,要显示上年四季度的情况,因此这里重新对年和季度做了设置
            IntYearNow = DateTime.Now.Year-1;
            StrYearNow = _intYearNow + "年";
            IntSeasonNow = 4;
            StrSeasonNow = "第四季度";
            //设置前一季度的年度和季度 其实变量名应该写intyearofpreseson的
            IntYearPre = IntYearNow;
            StrYearPre = IntYearPre + "年";
            IntSeasonPre = 3;
            StrSeasonPre = "第三季度";
            //设置同比季度的年度和季度
            IntYearYOY = IntYearNow - 1;
            StrYearYOY = IntYearYOY + "年";
            IntSeasonYOY = 4;
            StrSeasonYOY = "第四季度";
        }
        Global.Reset(IntYearNow, IntSeasonNow);
    }

    #endregion

    #region Func_统计云和一套表数据比对

    private async Task DataComparison()
    {
        StaticLogger.SystemInfo("执行统计云和一套表数据比对功能");
        List<DataComparisonOutcome> List_dedicatedOutcome;
        FuncOutCome outCome = AuditFunc.DataComparison(IntYearNow, IntSeasonNow,
            new string[] { "A209", "A210", "A211", "A212" }, out List_dedicatedOutcome);
        if (outCome.FuncSuccessCode == FuncOutComeCodeType.Success)
        {
            this.TextSchedule = "全部对比完毕,统计云和一套表数据一致";
            await MyMessagebox.ShowAsyncInMainWindow("全部对比完毕,统计云和一套表数据一致", outCome.Icon);
        }
        else
        {
            this.TextSchedule = outCome.FuncOutComeInfoArgs;
            await MyMessagebox.ShowAsyncInMainWindow("一套表和统计云数据比对结束,存在错误,请查看文本框和对话框", outCome.Icon);
            ComparisonOutcomeWindow window = new ComparisonOutcomeWindow();
            WeakReferenceMessenger.Default.Send(new TransmitView(window));
            WeakReferenceMessenger.Default.Send(List_dedicatedOutcome);
            window.Show(GetMainWindow());
        }
    }

    #endregion

    #region 从一套表下载数据

    /*private async Task<bool> ExecuteGetDataFromOld() //这里转移到了单独的一个窗口里面
    {
        // MyDataFolderOperator.CreateOrResetDownloadFolder();
        MyDataFolderOperator.CreateOrCheckAuditProgramFolderExist();
        this.TextSchedule = null;
        this.TextSchedule += "开始下载数据..." + Environment.NewLine;
        //判断桌面的审核程序文件夹下面是否已存在"下载的数据"文件夹
        //清空"下载数据"文件夹


        //如果已存在,调用网络操作的方法下载数据,如果已下载,返回true
        Dictionary<int, int> DownLoadSeaons = new Dictionary<int, int>();
        DownLoadSeaons.Clear();
        DownLoadSeaons.Add(IntYearNow, IntSeasonNow);
        if (this.IsSelectAllSeasons == true)
        {
            DownLoadSeaons.Add(IntYearPre, IntSeasonPre);
            DownLoadSeaons.Add(IntYearYOY, IntSeasonYOY);
        }

        bool isGetDataFromCountrySuccess = await 网络操作.Get国网数据(this.Str国网账号, this.Str国网密码, DownLoadSeaons,
            MyDataFolderOperator
                .DownloadFolderPathInAuditProgramFolder); // Path.Combine(MyDataFolderOperator.AuditProgramFolderPath, "下载的数据"));

        if (isGetDataFromCountrySuccess == false)
        {
            this.TextSchedule = string.Empty;
            this.TextSchedule += $"数据下载出现错误,请重试!" + Environment.NewLine;
            return false;
        }

        Task t3 = Task.Run(async () => await 网络操作.是否已经下载完毕Async());
        await t3;
        this.TextSchedule += "解压中..." + Environment.NewLine;
        FuncOutCome unzipOutcome =
            MyDataFolderOperator.UnZip(MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder);

        if (unzipOutcome.FuncSuccessCode != FuncOutComeCodeType.Success)
        {
            this.TextSchedule = string.Empty;
            this.TextSchedule += $"数据解压出错,请重试!" + Environment.NewLine + unzipOutcome.FuncOutComeInfoArgs +
                                 Environment.NewLine;
            return false;
        }

        MyProgressBar progressBar = new MyProgressBar();
        progressBar.Show();
        var progress = new Progress<int>(new Action<int>(value => progressBar.UpdateProgress(value)));

        string[] StrArrXlsFiles =
            Directory.GetFiles(MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder, "*.xls");
        FuncOutCome outCome =
            await Task.Factory.StartNew(() => XlsToSqlite.ExportXlsFilesToSqlite(StrArrXlsFiles, progress));
        if (outCome.FuncSuccessCode != FuncOutComeCodeType.Success)
        {
            this.TextSchedule = outCome.FuncOutComeInfoArgs;
            return false;
        }

        MyMessage ImoportToSqliteSuccessMsg = new MyMessage("一套表数据导入数据库成功,界面重新加载!");
        WeakReferenceMessenger.Default.Send(ImoportToSqliteSuccessMsg);
        InitializeDT();

        return true;

        //bool isGetDataFromProvinceSuccess = await 网络操作.getA406();
        //if (isGetDataFromCountrySuccess && isGetDataFromProvinceSuccess)
        //{
        //    this.TextSchedule += $"开始解压数据...{Environment.NewLine}";
        //    bool isDownloaded = await Task.Run(async () => await 是否下载完毕Async());
        //    if (isDownloaded)
        //    {
        //        TextSchedule += $"压缩包下载完成...{Environment.NewLine}";

        //    }
        //    else
        //    {
        //        return false;
        //    }

        //}
        //else
        //{
        //    this.TextSchedule = "程序运行错误";
        //}
    }*/

    #endregion

    #region 带参数的从一套表下载数据的方法

    /*
    private bool ExecuteGetDataFromOld(string p)
    {
        this.TextSchedule = null;
        this.TextSchedule += "开始下载数据...";
        //判断桌面的审核程序文件夹下面是否已存在"下载的数据"文件夹


        //如果已存在,调用网络操作的方法下载数据,如果已下载,返回true
        Dictionary<int, int> DownLoadSeaons = new Dictionary<int, int>();
        DownLoadSeaons.Clear();
        if (p.Equals("本季度"))
            DownLoadSeaons.Add(IntYearNow, IntSeasonNow);
        else if (p.Equals("上季度"))
        {
            DownLoadSeaons.Add(IntYearPre, IntSeasonPre);
        }
        else
        {
            DownLoadSeaons.Add(IntYearYOY, IntSeasonYOY);
        }


        bool isGetDataFromCountrySuccess = 网络操作.Get国网数据(this.Str国网账号, this.Str国网密码, DownLoadSeaons,
            Path.Combine(MyDataFolderOperator.AuditProgramFolderPath, "下载的数据")).Result;
        return true;
    }
    */

    #endregion

    #region 设置或改变年度季度是在属性方法里要调用的方法

    public void Reset()
    {
        //
        StrYearNow = IntYearNow.ToString() + "年";
        IntYearYOY = IntYearNow - 1;
        StrYearYOY = IntYearYOY.ToString() + "年";
        //
        StrSeasonNow = ConvertIntToStringOfSeason(IntSeasonNow);
        IntSeasonYOY = IntSeasonNow;
        StrSeasonYOY = ConvertIntToStringOfSeason(IntSeasonYOY);

        if (IntSeasonNow == 1)
        {
            IntSeasonPre = 4;
            IntYearPre = IntYearNow - 1;
        }
        else
        {
            IntSeasonPre = IntSeasonNow - 1;
            IntYearPre = IntYearNow;
        }

        StrYearPre = IntYearPre.ToString() + "年";
        StrSeasonPre = ConvertIntToStringOfSeason(IntSeasonPre);
    }

    private static string ConvertIntToStringOfSeason<T>(T IntSeason)
    {
        if (IntSeason is int intvalue)
        {
            if (intvalue == 1)
            {
                return "第一季度";
            }
            else if (intvalue == 2)
            {
                return "第二季度";
            }
            else if (intvalue == 3)
            {
                return "第三季度";
            }
            else if (intvalue == 4)
            {
                return "第四季度";
            }
            else
            {
                return "输入整形参数错误";
            }
        }
        else if (IntSeason is string strValue)
        {
            if (strValue.Equals("1") || strValue.Equals("一") || strValue.Equals("01"))
            {
                return "第一季度";
            }
            else if (strValue.Equals("2") || strValue.Equals("二") || strValue.Equals("02"))
            {
                return "第二季度";
            }
            else if (strValue.Equals("3") || strValue.Equals("三") || strValue.Equals("03"))
            {
                return "第三季度";
            }
            else if (strValue.Equals("4") || strValue.Equals("四") || strValue.Equals("04"))
            {
                return "第四季度";
            }
            else
            {
                return "输入字符串参数错误";
            }
        }
        else
        {
            return "数据类型错误";
        }
    }
    //public void SetStrYearNow()
    //{
    //    StrYearNow = IntYearNow.ToString() + "年";
    //}

    //public void SetYearOfPreSeason()
    //{
    //    if (IntSeasonNow == 1)
    //    {
    //        IntYearPre = IntYearNow - 1;
    //        StrYearPre = IntYearPre + "年";
    //    }
    //    else
    //    {
    //        IntYearPre = IntYearNow;
    //        StrYearPre = IntYearPre + "年";
    //    }
    //}

    //private void setYearOfYOYSeason()
    //{
    //    IntYearYOY = IntYearNow - 1;
    //    StrYearYOY = IntYearYOY + "年";
    //}

    //private void SetStrSeasonNow()
    //{
    //    if (IntSeasonNow == 1)
    //        StrSeasonNow = "第一季度";
    //    else if (IntSeasonNow == 2)
    //        StrSeasonNow = "第二季度";
    //    else if (_intSeasonNow == 3)
    //        StrSeasonNow = "第三季度";
    //    else
    //        StrSeasonNow = "第四季度";
    //}

    //private void SetSeasonPre()
    //{
    //    if (IntSeasonNow == 1)
    //    {
    //        IntSeasonPre = 4;
    //        StrSeasonPre = "第四季度";
    //    }
    //    else if (IntSeasonNow == 2)
    //    {
    //        IntSeasonPre = 1;
    //        StrSeasonPre = "第一季度";
    //    }
    //    else if (IntSeasonNow == 3)
    //    {
    //        IntSeasonPre = 2;
    //        StrSeasonPre = "第二季度";
    //    }
    //    else
    //    {
    //        IntSeasonPre = 3;
    //        StrSeasonPre = "第三季度";
    //    }
    //}

    //private void SetSeasonYOY()
    //{
    //    IntSeasonYOY = _intSeasonNow;
    //    if (IntSeasonYOY == 1)
    //        StrSeasonYOY = "第一季度";
    //    else if (IntSeasonYOY == 2)
    //        StrSeasonYOY = "第二季度";
    //    else if (IntSeasonYOY == 3)
    //        StrSeasonYOY = "第三季度";
    //    else if (IntSeasonYOY == 4) StrSeasonYOY = "第四季度";
    //}

    private void SendMsgToMainViewModel(string message)
    {
        var MessageSendor = new MyMessage(message);
        WeakReferenceMessenger.Default.Send(MessageSendor);
    }

    #endregion

    #region 绑定到view的collection

    private ObservableCollection<int> _clnOfRecentlyThreeYears =
        new()
        {
            DateTime.Now.Year - 3, DateTime.Now.Year - 2, DateTime.Now.Year - 1, DateTime.Now.Year,
            DateTime.Now.Year + 1
        };

    public ObservableCollection<int> ClnOfRecentlyThreeYears
    {
        get => _clnOfRecentlyThreeYears;
        set => SetProperty(ref _clnOfRecentlyThreeYears, value);
    }

    private ObservableCollection<int> _clnOfSeasons = new() { 1, 2, 3, 4 };

    public ObservableCollection<int> ClnOfSeasons
    {
        get => _clnOfSeasons;
        set => SetProperty(ref _clnOfSeasons, value);
    }

    #endregion

    public async Task ShowTheIcon()
    {
        Icon[] icons = new Icon[]
        {
            Icon.None,
            Icon.Battery,
            Icon.Database,
            Icon.Error,
            Icon.Folder,
            Icon.Forbidden,
            Icon.Info,
            Icon.Plus,
            Icon.Question,
            Icon.Setting,
            Icon.SpeakerLess,
            Icon.SpeakerMore,
            Icon.Stop,
            Icon.Stopwatch,
            Icon.Success,
            Icon.Warning,
            Icon.Wifi
        };
        for (int i = 0; i < icons.Length; i++)
        {
            await MyMessagebox.ShowAsyncInMainWindow("test", icons[i]);
        }
    }

    public void OpenAuditFolder()
    {
        StaticLogger.SystemInfo("打开审核程序文件夹");
        string auditFolderPath = MyDataFolderOperator.AuditProgramFolderPath;
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            Process.Start("explorer.exe", auditFolderPath);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            Process.Start("xdg-open", auditFolderPath); // 对于大多数Linux桌面环境
            // 如果你知道使用的具体文件管理器，也可以直接调用，例如：
            // Process.Start("nautilus", folderPath); // GNOME
            // Process.Start("dolphin", folderPath);  // KDE
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            Process.Start("open", auditFolderPath);
        }
    }

    public async Task ModifyCityCountryTownAsync()
    {
        StaticLogger.SystemInfo("执行县乡名称修正操作");
        List<FuncOutCome> modifyOutcomes = Modify.ModityAll15Tables(StrYearNow, StrSeasonNow, StrYearPre, StrSeasonPre,
            StrYearYOY, StrSeasonYOY);
        if (modifyOutcomes.Count > 0)
        {
            this.TextSchedule = string.Empty;
            foreach (var outcome in modifyOutcomes)
            {
                this.TextSchedule += " " + outcome.FuncOutComeInfoArgs + Environment.NewLine;
            }

            await MyMessagebox.ShowAsyncInMainWindow("修正完成,但存在问题,请看文本框", Icon.Info);
        }
        else
        {
            await MyMessagebox.ShowAsyncInMainWindow("修正完成!", Icon.Success);
        }

        StaticLogger.SystemInfo("县乡名称修正完成");
        //以下是加进度条没有成功,可能跟返回的是list有关系
        //MyProgressBar _progressBar = new MyProgressBar();
        ////_progressBar.Show();
        ////var progress = new Progress<int>(value => _progressBar.UpdateProgress(value));
        //// 确保进度条在主线程中显示
        //await Dispatcher.UIThread.InvokeAsync(() => _progressBar.Show());

        //var progress = new Progress<int>(value =>
        //{
        //    //确保在ui线程更新进度条
        //    Dispatcher.UIThread.InvokeAsync(() => _progressBar.UpdateProgress(value));
        //});

        //List<FuncOutCome> modifyOutcomes = await Task.Factory.StartNew(()=>  Modify.ModityAll15Tables(StrYearNow, StrSeasonNow, StrYearPre, StrSeasonPre, StrYearYOY, StrSeasonYOY,progress));
        //// 确保进度条在主线程中关闭
        //await Dispatcher.UIThread.InvokeAsync(() => _progressBar.Close());
        //if (modifyOutcomes.Count > 0)
        //{
        //    this.TextSchedule = string.Empty;
        //    foreach (var outcome in modifyOutcomes)
        //    {
        //        this.TextSchedule += " " + outcome.FuncOutComeInfoArgs + Environment.NewLine;
        //    }
        //    await Task.Run(async ()=> await MyMessagebox.ShowAsyncInMainWindow("修正完成,但存在问题,请看文本框", Icon.Info));
        //}
        //else
        //{
        //    await MyMessagebox.ShowAsyncInMainWindow("修正完成!", Icon.Success);

        //}
    }

    public async Task DeleteSingleTableInDBAsync()
    {
        StaticLogger.SystemInfo("执行删除数据库中单个表的操作");
        if (SelectedTableMsgs != null)
        {
            string tableNameInDB = SelectedTableMsgs.表名称;

            var deleteOperator = MyDBOperator.DBOperatorInstance;
            if (deleteOperator.CheckIfTableExists(tableNameInDB) == false)
            {
               await MyMessagebox.ShowAsyncInMainWindow($"数据库中不存在{tableNameInDB}表", Icon.Error);
                StaticLogger.SystemInfo($"数据库中不存在{tableNameInDB}表");
            }
            else
            {
                deleteOperator.DeleteTable(tableNameInDB);
                StaticLogger.SystemInfo("删除数据库中单个表成功");
               
                InitializeDT();
                await MyMessagebox.ShowAsyncInMainWindow($"删除成功", Icon.Success);
            }
        }
        else
        {
           await MyMessagebox.ShowAsyncInMainWindow("未选中要删除的行", Icon.Warning);
        }

    }
}